import 'package:flutter/material.dart';

// ignore: must_be_immutable
class GridViewCase extends StatefulWidget {
  GridViewCase({super.key});
  List<String> arr = [];
  @override
  State createState() => _GridViewCaseState();
}

class _GridViewCaseState extends State<GridViewCase> {
  @override
  void initState() {
    for (var i = 0; i < 10; i++) {
      widget.arr.add('第${i + 1}个');
    }
    super.initState();
  }

  Widget getListItem(int index) {
    return Container(
      color: index % 2 == 0 ? Colors.amber : Colors.blueAccent,
      child: Text(widget.arr[index]),
    );
  }

  @override
  Widget build(BuildContext context) {
    //动态渲染子组件
    // return GridView.builder(
    //   gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
    //       crossAxisCount: 3,
    //       childAspectRatio: 1,
    //       mainAxisSpacing: 10,
    //       crossAxisSpacing: 10),
    //   itemBuilder: (context, int index) {
    //     return getListItem(index);
    //   },
    //   itemCount: widget.arr.length,
    // );

    // return GridView(
    //   gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
    //       crossAxisCount: 3, //交叉轴数量、横轴数量
    //       mainAxisSpacing: 10, //主轴间距
    //       crossAxisSpacing: 20, //横轴间距
    //       // mainAxisExtent: 10, //容器在主轴宽度
    //       childAspectRatio: 1.5 //宽高比
    //       ),
    //   children: [
    //     Container(
    //       color: Colors.amber,
    //     ),
    //     Container(
    //       color: Colors.red,
    //     ),
    //     Container(
    //       color: Colors.deepPurpleAccent,
    //     ),
    //     Container(
    //       color: Colors.lightBlue,
    //     ),
    //   ],
    // );

// 设置宽度自动换行
    return GridView.extent(
      maxCrossAxisExtent: 200,
      mainAxisSpacing: 10, //主轴间距
      crossAxisSpacing: 20, //横轴间距
      // mainAxisExtent: 10, //容器在主轴宽度
      childAspectRatio: 1.5, //宽高比
      children: [
        Container(
          color: Colors.amber,
        ),
        Container(
          color: Colors.red,
        ),
        Container(
          color: Colors.deepPurpleAccent,
        ),
        Container(
          color: Colors.lightBlue,
        ),
      ],
    );
  }
}
